package com.hc.java.transaction;

import java.util.concurrent.CompletableFuture;

/**
 * 最原始的方法，Thread run()重写
 *
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/6/20 20:34
 */
public class T06_03_AliQuestionAboutCF {
    public static void main(String[] args) throws Exception {
        MyTask t1 = new MyTask("t1", 3, true);
        MyTask t2 = new MyTask("t2", 4, true);
        MyTask t3 = new MyTask("t3", 1, false);

        CompletableFuture f1 = CompletableFuture.supplyAsync(t1::call).thenAccept(r -> callback(r));
        CompletableFuture f2 = CompletableFuture.supplyAsync(t2::call).thenAccept(r -> callback(r));
        CompletableFuture f3 = CompletableFuture.supplyAsync(t3::call).thenAccept(r -> callback(r));

        System.in.read();
    }

    private static void callback(Boolean r) {
        if (false == r) {
            // 处理结束流程
            // 通知其他线程结束（回滚）
            // 超时处理
            System.exit(0);
        }
    }

    private enum Result {
        NOTEND, SUCCESSED, FAILED, CANCELLED
    }

    private static class MyTask {
        private String name;
        private int timeInSeconds;
        private boolean success;

        public MyTask(String name, int timeInSeconds, boolean success) {
            this.name = name;
            this.timeInSeconds = timeInSeconds;
            this.success = success;
        }

        public Boolean call() {
            // 模拟业务执行时间
            // 实际中时间不固定，可能在处理计算任务，或者是IO任务
            try {
                Thread.sleep(timeInSeconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + " 任务结束！");
            return success;
        }
    }
}
